package com.zyk.scaffold.gateway.service.impl;

import com.zyk.scaffold.gateway.components.CacheComponent;
import com.zyk.scaffold.gateway.enums.GatewayErrorCodeEnum;
import com.zyk.scaffold.gateway.service.TokenService;
import com.zyk.scaffold.oauth.dto.TokenInfoDTO;
import com.zyk.scaffold.oauth.rpc.OauthRpcService;
import com.zyk.scaffold.common.basic.BasicException;
import com.zyk.scaffold.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class TokenServiceImpl implements TokenService {
    @DubboReference
    private OauthRpcService oauthRpcService;

    @Autowired
    private CacheComponent cacheComponent;

    @Override
    public TokenInfoDTO analysisAccessToken(String accessToken) {
        return cacheComponent.getTokenInfoDTO(accessToken, key -> {
            TokenInfoDTO tokenInfoDTO = null;
            try{
                tokenInfoDTO = oauthRpcService.analysisAccessToken(key);
            }catch (Exception ex){
                if(ex instanceof BasicException){
                    throw ex;
                }else {
                    log.error("analysis access-token error:", ex);
                    throw new BusinessException(GatewayErrorCodeEnum.TOKEN_INVALID_FAIL);
                }
            }
            return tokenInfoDTO;
        });
    }
}
